
import { RoomModel } from "../../hall_server/model/RoomModel";
import { RoomPlayer } from "../../hall_server/model/RoomPlayer";

import { Config } from "../config/Config";
import { RoomConfig } from "../config/RoomConfig";
import { ServerConfig } from "../config/ServerConfig";
import { SocketConnection } from "../engine/socketserver/socket/SocketConnection";
import { SocketConnectionManager } from "../engine/socketserver/socket/SocketConnectionManager";
import { Logger } from "../engine/utils/Logger";
import { JhaoProto } from "../lib/net/protobuf/jhaoproto";
import { ResponseModel } from "../model/ResponseModel";
import { RoomManager } from "./RoomManager";

const check_delete_room_time_inteval: number = 1000;//1秒检查一次
const Must_delete_room_time: number = 1000 * 60 * 60 * 24; //120分钟强制解散

const check_leave_room_time_inteval: number = 1000;  //1秒检查一次
const Must_leave_room_time: number = 1000 * 30; //30秒不准备离开

export class TimerManager {

    public static instance: TimerManager = new TimerManager();

    private last_check_delete_room_time: number = 0
    private last_check_leave_room_time: number = 0


    public checkTimer(now: number) {
        this.checkPlayerOnline(now)
        this.checkDeleteRoom(now)
        this.checkLeaveRoom(now)

    }

    private async checkPlayerOnline(now: number) {
        if (Config.serverType == Config.ServerType_List.hall_server) {
            return
        }
        RoomModel.roomMap.forEach((room: RoomModel, key: number) => {
            let needNotify:boolean = false
            for (let i = 0; i < room.playerList.length; i++) {
                let player: RoomPlayer = room.playerList[i]
                if (player) {
                    if (SocketConnectionManager.instance.isUserOnline(player.userid)) {
                        if (!player.isOnline) {
                            player.isOnline = true
                            needNotify = true
                        }
                    }else{
                        if (player.isOnline) {
                            player.isOnline = false
                            needNotify = true
                        }
                    }
                }
            }
            if(needNotify){
                RoomManager.instance.notify_player_update(room)
            }

        });
    }

    private async checkLeaveRoom(now: number) {
        if (Config.serverType == Config.ServerType_List.hall_server) {
            return
        }
        if (now - this.last_check_leave_room_time >= check_leave_room_time_inteval) {
            this.last_check_leave_room_time = now;
            RoomModel.roomMap.forEach((value: RoomModel, key: number) => {
                let leavePlayerList: Array<RoomPlayer> = []
                if (value.num_of_turns <= 0) {
                    for (let i = 0; i < value.playerList.length; i++) {
                        let player: RoomPlayer = value.playerList[i]
                        if (player && !player.ready) {
                            if (now - player.joinTime >= Must_leave_room_time) {
                                leavePlayerList.push(player)
                            }
                        }
                    }
                    if (leavePlayerList.length > 0) {
                        Logger.log("30秒不准备被踢出==", leavePlayerList)
                        for (let i = 0; i < leavePlayerList.length; i++) {
                            let player: RoomPlayer = leavePlayerList[i]
                            RoomManager.instance.leave_room(value.room_id, player.userid)
                        }
                    }
                }
            });
        }
    }

    private async checkDeleteRoom(now: number) {
        if (Config.serverType == Config.ServerType_List.hall_server) {
            return
        }
        if (now - this.last_check_delete_room_time >= check_delete_room_time_inteval) {
            this.last_check_delete_room_time = now;
            let deleteRoomList: Array<JhaoProto.IRoomModel> = []
            let deleteRoomIdList: Array<number> = []
            let deleteReasonList: Array<string> = []
            RoomModel.roomMap.forEach((room: JhaoProto.IRoomModel, key: number) => {
                let needDelete: boolean = false
                if (now - room.createTime >= Must_delete_room_time) { //120分钟强制解散房间
                    needDelete = true
                    deleteReasonList.push("120分钟强制解散房间")
                }
                else {
                    if (room.gameInfoBase.applyDismissUserid > 0) { //时间到解散投票截止,自动解散
                        let cd: number = room.roomConfigBase.dismissTime * 1000;
                        if (now >= (room.gameInfoBase.applyDismissTime + cd)) {
                            needDelete = true
                            deleteReasonList.push("解散投票时间到自动解散")
                        }
                    }
                }
                if (needDelete) {
                    deleteRoomList.push(room)
                    deleteRoomIdList.push(room.roomId)
                }
                if (!needDelete) {
                    this.checkRoomGameLogic(room, now)
                    this.checkAutoReady(room, now)
                    // this.checkAutoReleaseZiyou(room, now)
                }
            });

            if (deleteRoomIdList.length > 0) {
                RoomManager.instance.delete_room(deleteRoomIdList, deleteRoomList, deleteReasonList)
            }

        }
    }

    private async checkRoomGameLogic(room: JhaoProto.IRoomModel, now: number) {
        // if (room.game_info instanceof DdzGameInfo) {
        //     ddz_Gamemanager.instance.checkTurnTimeEnd(room, now)
        // }
        // else if (room.game_info instanceof paodekuai_GameInfo) {
        //     paodekuai_Gamemanager.instance.checkTurnTimeEnd(room, now)
        // }
        // else if (room.game_info instanceof jianziding_GameInfo) {
        //     jianziding_Gamemanager.instance.checkTurnTimeEnd(room, now)
        // }
        // else if (room.game_info instanceof huanghua_mj_GameInfo) {
        //     huanghua_mj_Gamemanager.instance.checkTurnTimeEnd(room, now)
        // }
        // else if (room.game_info instanceof cangxian_mj_GameInfo) {
        //     cangxian_mj_Gamemanager.instance.checkTurnTimeEnd(room, now)
        // }
        // else if (room.game_info instanceof dazhonger_mj_GameInfo) {
        //     dazhonger_mj_Gamemanager.instance.checkTurnTimeEnd(room, now)
        // }
    }


    private async checkAutoReady(room: JhaoProto.IRoomModel, now: number) {
        if (ServerConfig.nowServerConfig.id == room.serverId) { //游戏服自动准备
            if (room.roomType == RoomConfig.Room_Type.Ziyou) {
                // if (room.num_of_turns >= 1 && room.num_of_turns <= room.conf["jushu"]) {
                //     let playerList: Array<RoomPlayer> = room.playerList;
                //     let isGameStart: boolean = false
                //     let respModel: ResponseModel = new ResponseModel()
                //     for (let i = 0; i < playerList.length; i++) {
                //         let player: RoomPlayer = playerList[i]
                //         if (player) {
                //             if (!player.ready) {
                //                 if (room.lastCheckAutoReadyTIme == 0) {
                //                     room.lastCheckAutoReadyTIme = now
                //                     break
                //                 }
                //                 if (now - room.lastCheckAutoReadyTIme >= 60 * 1000) { //60秒自动准备
                //                     if (player.score >= room.conf["minCharge"]) {
                //                         player.ready = true;
                //                         if (room.isAllReady()) {
                //                             isGameStart = true
                //                         }
                //                         let conn: SocketConnection = SocketConnectionManager.instance.getSocketConnectionByUserid(player.userid)
                //                         if (conn) {
                //                             respModel.data = room.playerList
                //                             // conn.createMsgToClient(0, ProtoConfig.notify_update_player, respModel)
                //                         }
                //                     }
                //                 }
                //             }
                //         }
                //     }
                //     if (isGameStart) {
                //         RoomManager.instance.notify_game_start(room)
                //     }
                // }
            }
        }
    }

    private async checkAutoReleaseZiyou(room: RoomModel, now: number) {
        if (ServerConfig.nowServerConfig.id == room.server_id) { //游戏服自动准备
            if (room.roomType == RoomConfig.Room_Type.Ziyou) {
                if (room.num_of_turns >= 1) {
                    let playerList: Array<RoomPlayer> = room.playerList;
                    let isNeedRelease: boolean = false
                    let releaseSeason: string = ""

                    for (let i = 0; i < playerList.length; i++) {
                        let player: RoomPlayer = playerList[i]
                        if (player && player.chargeEndTime > 0) {
                            if (now >= player.chargeEndTime && player.score <= room.conf["minCharge"]) { //不够钱够钟就解散
                                if (player.score >= room.conf["minCharge"]) {
                                    isNeedRelease = true
                                    releaseSeason = player.nick_name + "金豆不足时间到解散房间"
                                    break
                                }
                            }
                        }
                    }
                    if (isNeedRelease) {
                        RoomManager.instance.delete_room([room.room_id], [room], [releaseSeason])
                    }
                }
            }
        }
    }

}